﻿#region License
//------------------------------------------------------------
// Copyright (c) Denis Vuyka.  All rights reserved.
// This source code is subject to terms and conditions of the 
// Microsoft Reciprocal License (Ms-RL) License for Carcass. 
// A copy of the license can be found in the License.txt file 
// at the root of this distribution. 
// By using this source code in any fashion, you are agreeing 
// to be bound by the terms of the 
// Microsoft Reciprocal License (Ms-RL) License
// You must not remove this notice from this software.
//------------------------------------------------------------
#endregion

using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace Carcass.Contents
{
  [Export(typeof(IDocumentService))]
  internal sealed class DocumentService : IDocumentService
  {
    [Import(GlobalContracts.DocumentReader)]
    private ExportCollection<IDocumentReader, IDocumentReaderMetadata> DocumentReaders { get; set; }

    [Import]
    private DocumentFactory DocumentFactory { get; set; }

    [Import(GlobalContracts.Document, AllowRecomposition = true)]
    public ExportCollection<IDocument, IDocumentMetadata> DocumentTemplates { get; private set; }

    public Export<IDocument, IDocumentMetadata> LoadDocument(Uri uri)
    {
      string path = uri.LocalPath;
      string extension = Path.GetExtension(path);

      IDocumentReader reader = GetDocumentReader(extension);

      Export<IDocument, IDocumentMetadata> document = null;

      using (FileStream stream = File.OpenRead(path))
      {
        document = reader.Read(stream);
      }

      return document;
    }
        
    public Export<IDocument, IDocumentMetadata> CreateDocument(string documentType)
    {
      return DocumentFactory.CreateDocument(documentType);
    }

    public Export<IDocument, IDocumentMetadata> CreateDocument(IDocumentMetadata metadata)
    {
      return DocumentFactory.CreateDocument(metadata.DocumentType);
    }

    public string[] GetReaderFilters()
    {
      List<string> filters = new List<string>();
      
      foreach (var reader in DocumentReaders)
      {
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("{0} |", reader.MetadataView.FilterTitle);

        foreach (string extension in reader.MetadataView.Extension)
          sb.AppendFormat("*{0};", extension);

        filters.Add(sb.ToString());
      }

      return filters.ToArray();
    }

    #region Private members

    private IDocumentReader GetDocumentReader(string extension)
    {
      return DocumentReaders
        .FirstOrDefault(reader => reader.MetadataView.Extension.Contains(extension))
        .GetExportedObject();
    }

    #endregion
  }
}
